//---------------------------------------------------------------------------------
// Copyright (c) 2008 David Vescovi.  All rights reserved.
//
// Example managed SPI bus interface to AD5232 digital pot.
//
//---------------------------------------------------------------------------------
using System;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using OpenNETCF;
using OpenNETCF.WindowsCE;
using Gumstix;

namespace SPI_Bus_test
{
    public partial class Form1 : Form
    {

        /// <summary>
        /// SPI bus object instance
        /// </summary>
        SPI spi;

        public Form1()
        {
            InitializeComponent();
            spi = new SPI();

            UInt16 rxdata16a = 0;
            UInt16 rxdata16b = 0;
            UInt16 rxdata16c = 0;
            UInt16 rxdata16d = 0;
            UInt16 rxdata16e = 0;

//            spi.Loopback = true;
            spi.Loopback = false;
                                                            // see page 7 of AD5232 data sheet
//            rxdata16a = spi.Exchange((UInt16)0xb040,true,true); // pol and pha true, Loads 0x40 to RDAC1

            rxdata16a = spi.Exchange((UInt16)0xb040);       // Loads 0x40 to RDAC1
            rxdata16b = spi.Exchange((UInt16)0x2000);       // Save copy of RDAC1
            Thread.Sleep(30);
            rxdata16c = spi.Exchange((UInt16)0xb180);       // Loads 0x80 data to RDAC2
            rxdata16d = spi.Exchange((UInt16)0x2100);       // Save copy of RDAC2 to EEMEM1
            Thread.Sleep(30);

            Console.WriteLine("data 16a = 0x{0:X}", rxdata16a); // dump it
            Console.WriteLine("data 16b = 0x{0:X}", rxdata16b);
            Console.WriteLine("data 16c = 0x{0:X}", rxdata16c);
            Console.WriteLine("data 16d = 0x{0:X}", rxdata16d);

            rxdata16e = spi.Exchange((UInt16)0x32a5);       // 0xA5 to USER1
            Thread.Sleep(30);
            rxdata16e = spi.Exchange((UInt16)0x3380);       // 0x80 to USER2
            Thread.Sleep(30);
            rxdata16e = spi.Exchange((UInt16)0x9200);       // Prepare to read USER1
            rxdata16e = spi.Exchange((UInt16)0x0000);       // nop for read
            Console.WriteLine("data write 0xa5  read = 0x{0:x}", (rxdata16e & 0x00ff));
            rxdata16e = spi.Exchange((UInt16)0x9300);       // Prepare to read USER2
            rxdata16e = spi.Exchange((UInt16)0x0000);       // nop for read
            Console.WriteLine("data write 0x80  read = 0x{0:x}", (rxdata16e & 0x00ff));

        }
    }
}